<template>
  <div>
    <el-input
      v-model="pagination.title"
      placeholder="新闻标题"
      style="width: 200px"
      class="filter-item"
    ></el-input>
    <el-button id="querybutton" class="dalfBut" @click="queryNewsByTitle"
      >查询</el-button
    >
    <button id="add-button" @click="dialogAddFormVisible = true">新增</button>
    <el-table :data="newsData" border style="width: 100%">
      <el-table-column type="index" label="序号" width="60"> </el-table-column>
      <el-table-column prop="title" label="新闻标题"></el-table-column>
      <el-table-column
        prop="category.name"
        label="新闻分类"
        width="120"
      ></el-table-column>
      <el-table-column
        prop="publishTime"
        label="发布时间"
        width="160"
      ></el-table-column>
      <el-table-column
        prop="readTimes"
        label="阅读次数"
        width="120"
      ></el-table-column>
      <el-table-column prop="status" label="状态" width="120"></el-table-column>
      <el-table-column prop="thumpUp" label="点赞次数" width="120">
      </el-table-column>

      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="medium"
            style="color: #409eff"
            @click="openEditDialog(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="text"
            size="medium"
            style="color: red"
            @click="deleteNews(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :current-page="pagination.page"
      :page-size="pagination.pageSize"
      layout="total, prev, pager, next, jumper"
      :total="pagination.total"
      @current-change="handleCurrentChange"
    >
    </el-pagination>

    <!-- 新增 -->
    <el-dialog
      title="新增新闻信息"
      :visible.sync="dialogAddFormVisible"
      :show-close="false"
    >
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item label="新闻标题" prop="title">
          <el-input v-model.trim="form.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="新闻内容" prop="content" label-width="80px">
          <!-- <el-input
            v-model.trim="form.content"
            autocomplete="off"
            type="textarea"
          ></el-input> -->
          <!-- 使用富文本编辑器 -->
          <Tinymce v-model="form.content" :height="240"></Tinymce>
        </el-form-item>
        <el-form-item label="新闻分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择">
            <el-option
              v-for="item in categoryData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取 消</el-button>
        <el-button type="primary" @click="addNews()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑 -->
    <el-dialog
      title="编辑新闻信息"
      :visible.sync="dialogEditFormVisible"
      :show-close="false"
    >
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item label="新闻标题" prop="title">
          <el-input v-model.trim="form.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="新闻内容" prop="content" label-width="80px">
          <!-- <el-input
            v-model.trim="form.content"
            autocomplete="off"
            type="textarea"
          ></el-input> -->
          <!-- 使用富文本编辑器 -->
          <Tinymce id="tinymce" v-model="form.content" :height="240"></Tinymce>
        </el-form-item>
        <el-form-item label="新闻分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择">
            <el-option
              v-for="item in categoryData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取消</el-button>
        <el-button type="primary" @click="handleEidt()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import moment from 'moment'
import {
  getNewsPagination,
  removeNews,
  getNewsCategory,
  addNews,
  getNewsById
} from '@/api/news'
export default {
  components: { Tinymce },
  data() {
    return {
      // 新闻信息数据
      newsData: [],
      // 分页的数据信息
      pagination: {
        page: 1,
        pageSize: 8,
        title: ''
      },
      // 分类信息数据
      categoryData: [],
      // 新增框是否展示
      dialogAddFormVisible: false,
      dialogEditFormVisible: false,
      // form表单数据
      form: {
        id: '',
        title: '',
        content: '',
        categoryId: '',
        photoId: ''
      },
      // 校验规则
      rules: {
        title: [
          { required: true, message: '新闻标题为必填项', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '新闻内容为必填项', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '新闻分类名称为必填项', trigger: 'blur' }
        ]
      }
    }
  },
  // 监视属性
  watch: {
    // 监视新增框，关闭就清空表单数据
    dialogAddFormVisible: function (value) {
      if (!value) {
        this.clearForm()
      }
    },
    // 监视编辑框，关闭就清空表单数据
    dialogEditFormVisible: function (value) {
      if (!value) {
        this.clearForm()
      }
    }
  },
  created() {
    this.getData()
    this.getCategoryInfo()
  },
  methods: {
    // 获取分类信息数据
    async getData() {
      this.newsData = []
      const response = await getNewsPagination(this.pagination)
      // 拿到数据
      if (response.status === 200) {
        this.pagination.page = response.data.page
        this.pagination.pageSize = response.data.pageSize
        this.pagination.total = response.data.total
        this.newsData = response.data.list
        this.formatDate()
      } else {
        this.$message.error(response.message)
      }
    },
    // 获取指定分页信息
    handleCurrentChange(currentPage) {
      this.pagination.page = currentPage
      this.getData()
    },
    // 通过新闻标题名查询新闻
    queryNewsByTitle() {
      this.pagination.page = 1
      this.getData()
    },
    // 获取分类信息
    async getCategoryInfo() {
      const response = await getNewsCategory()
      if (response.status === 200) {
        this.categoryData = response.data
      }
    },
    // 格式化发布时间
    formatDate() {
      this.newsData.forEach((item) => {
        item.publishTime = moment(item.publishTime).format(
          'YYYY-MM-DD HH:mm:ss'
        )
      })
    },
    // 根据id删除新闻
    deleteNews(newsInfo) {
      this.$confirm('此操作将永久删除该新闻信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const response = await removeNews(newsInfo.id)
          if (response.status === 200) {
            this.pagination.page = 1
            this.getData()
            this.$message({
              type: 'success',
              message: '删除成功'
            })
          } else {
            this.$message.error(response.message)
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '操作取消'
          })
        })
    },
    // 新增新闻
    async addNews() {
      if (!this.form.title || !this.form.content || !this.form.categoryId) {
        this.$refs['form'].validate((valid) => {
          if (!valid) {
            return false
          }
        })
        return
      }
      const response = await addNews(this.form)
      if (response.status === 200) {
        this.getData()
        this.clearForm()
        this.$message.success(response.message)
      } else {
        this.$message.error(response.message)
      }
      this.dialogAddFormVisible = false
    },
    // 取消新增，编辑框
    cancel() {
      this.dialogAddFormVisible = false
      this.dialogEditFormVisible = false
      this.$message.info('操作取消')
    },
    // 更新分类信息
    async handleEidt() {
      if (!this.form.title || !this.form.content || !this.form.categoryId) {
        this.$refs['form'].validate((valid) => {
          if (!valid) {
            return false
          }
        })
        return
      }
      const response = await addNews(this.form)
      if (response.status === 200) {
        this.getData()
        this.clearForm()
        this.$message.success(response.message)
      } else {
        this.$message.error(response.message)
      }
      this.dialogEditFormVisible = false
    },
    // 打开编辑
    async openEditDialog(categoryInfo) {
      const response = await getNewsById(categoryInfo.id)
      if (response.status === 200) {
        if (response.data === null) {
          this.$message.error('数据未同步')
          this.getData()
        } else {
          this.form = response.data
          this.dialogEditFormVisible = true
        }
      } else {
        this.$message.error(response.message)
      }
    },
    // 清空form表单
    clearForm() {
      this.form.id = ''
      this.form.title = ''
      this.form.content = ''
      this.form.categoryId = ''
      this.form.photoId = ''
    }
  }
}
</script>

<style scoped lang="scss">
#add-button {
  width: 80px;
  height: 38px;
  margin-bottom: 5px;
  margin-left: 10px;
  font-size: medium;
  font-weight: 700;
  color: #fff;
  background-color: #4c84ee;
  border: none;
  border-radius: 7px;

  &:hover {
    cursor: pointer;
    background-color: #4c85eec6;
    // color: #4c84ee;
  }
}

#querybutton {
  margin-left: 15px;
}
</style>
